package com.terran4j.demo.api2doc;

import com.terran4j.commons.api2doc.annotations.Api2Doc;
import com.terran4j.commons.api2doc.annotations.ApiComment;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

@Api2Doc(value = "user", name = "用户相关接口")
@RestController
@RequestMapping(value = "/users")
public class UserController {

    // 当作 id 生成器。
    private AtomicLong idCount = new AtomicLong(0);

    private Map<Long, User> users = new ConcurrentHashMap<Long, User>();

    @PostConstruct
    public void init() {
        registUser("刘备");
        registUser("关羽");
        registUser("张飞");
    }

    @ApiComment("根据指定的用户名称，注册一个新用户")
    @RequestMapping(value = "", method = RequestMethod.POST,
            name = "注册新用户")
    public User registUser(String name) {
        long id = idCount.incrementAndGet();
        User user = new User(id, name);
        users.put(id, user);
        return user;
    }

    @RequestMapping(value = "", method = RequestMethod.GET,
            name = "获取用户列表")
    public List<User> getUsers() {
        return new ArrayList<User>(users.values());
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET,
            name = "获取用户详细信息")
    public User getUser(@PathVariable Long id) {
        return users.get(id);
    }

    @ApiComment("更新指定用户的用户名称")
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT,
            name = "更新用户名")
    public void putUser(@PathVariable Long id, String name) {
        users.get(id).setName(name);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE,
            name = "删除用户")
    public void deleteUser(@PathVariable Long id) {
        users.remove(id);
    }

}
